package com.efounder.chat.utils;

import android.text.Spannable;

import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.struct.StructFactory;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.struct.IMStruct002;
import com.efounder.pansoft.chat.emoji.widget.EmoticonsEditText;
import com.utilcode.util.LogUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 文本消息以及群@ at消息处理
 *
 * @autor yqs
 * @date 2018/10/13
 **/
public class TextFormatMessageUtil {

    /**
     * 从输入框文本中是否包含@
     *
     * @param inputText
     * @return
     */
    public static boolean editTextHasAt(CharSequence inputText) {
        if (inputText instanceof Spannable) {
            //如果是span 过滤一下 @的信息
            EmoticonsEditText.SpData[] atSpans = (((Spannable) inputText).getSpans(0,
                    inputText.length(), EmoticonsEditText.SpData.class));

            if (atSpans != null && atSpans.length > 0) {
                return true;
            } else {
                //不是@消息当成文本发送
                return false;
            }
        } else {
            //文本消息
            return false;
        }

    }

    /**
     * 从输入框解析发送的消息获取Imstruct
     *
     * @param inputText 输入的文本
     * @param chatType  聊天类型
     * @return
     */
    public static IMStruct002 getSendTextImStruct(CharSequence inputText, byte chatType) {
        if (inputText instanceof Spannable) {
            //如果是span 过滤一下 @的信息
            EmoticonsEditText.SpData[] atSpans = (((Spannable) inputText).getSpans(0,
                    inputText.length(), EmoticonsEditText.SpData.class));

            if (atSpans != null && atSpans.length > 0) {
                //{"type":"at","content":"@王伟龙 吃饭，@郑杰 测试","ID":[{"userId":200348,"text":"@王伟龙","start":0,"length":4},{"userId":212375,"text":"@郑杰","start":8,"length":3}]}
                JSONObject jsonObject = new JSONObject();
                JSONArray idsArray = new JSONArray();
                jsonObject.put("type", "at");
                jsonObject.put("content", inputText.toString());

                for (EmoticonsEditText.SpData atSpan : atSpans) {
                    String content = atSpan.getShowContent().toString();
                    int start = ((Spannable) inputText).getSpanStart(atSpan);
                    int end = ((Spannable) inputText).getSpanEnd(atSpan);
                    int userId = atSpan.getUserId();
                    LogUtils.e(content, start, end, userId);
                    JSONObject atObject = new JSONObject();
                    atObject.put("userId", userId);
                    atObject.put("text", content);
                    atObject.put("start", start);
                    atObject.put("length", end - start);
                    idsArray.add(atObject);
                }
                jsonObject.put("ID", idsArray);
                LogUtils.e("@消息的json:", jsonObject.toString());
                return StructFactory.getInstance().createJsonTextStruct(jsonObject.toString(), chatType);
            } else {
                //不是@消息当成文本发送
                return StructFactory.getInstance().createTextStruct(inputText.toString(), chatType);
            }
        } else {
            //文本消息
            return StructFactory.getInstance().createTextStruct(inputText.toString(), chatType);

        }
    }


    /**
     * 解析json文本消息 消息类型11
     *
     * @param message 接收的消息体
     * @return 文本消息
     */
    public static String disposeJsonTextMessage(IMStruct002 message) {
        String messageText = message.getMessage();
        try {
            net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(messageText);
            String type = jsonObject.optString("type", "");
            if ("at".equals(type)) {
                //@消息
                return jsonObject.optString("content", "");
            } if ("text".equals(type)) {
                //普通文本消息
                return jsonObject.optString("content", "");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return messageText;
    }

    /**
     * 检查消息中是否@了我
     *
     * @param message 接收的消息体
     * @return 文本消息
     */
    public static boolean checkHasAtMe(IMStruct002 message) {
        if (message.getMessageChildType() != MessageChildTypeConstant.subtype_format_text){
            //不是@消息
            return false;
        }
        String messageText = message.getMessage();
        try {
            net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(messageText);
            String type = jsonObject.optString("type", "");
            if ("at".equals(type)) {
                JSONArray array = jsonObject.getJSONArray("ID");
                int myUserId = Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID));
                for (int i = 0; i < array.size(); i++) {
                    JSONObject item = array.getJSONObject(i);
                    if (item.optInt("userId", 0) == myUserId) {
                        return true;
                    }
                }
            } else {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 将未读的@消息存到EV中，显示在列表中
     * @param imStruct002 msg
     */
    public static void saveMentionHintEV(IMStruct002 imStruct002) {
        if (TextFormatMessageUtil.checkHasAtMe(imStruct002)) {
            String mentionMessage = imStruct002.getToUserId() + "" + imStruct002.getToUserType() + "@";
            EnvironmentVariable.setProperty(mentionMessage, "true");
        }
    }

    /**
     * 将EV中存的@消息设为已读，不在列表显示提醒
     */
    public static void clearMentionHintEV(String userId, String userType) {
        String mentionMessage = userId + userType +"@";
        EnvironmentVariable.setProperty(mentionMessage, "false");
    }

    /**
     * 是否有未读的@消息
     * @param userId userId
     * @param userType 群聊
     * @return true or false
     */
    public static boolean hasUnreadMentionMessage(String userId, String userType) {
        return (EnvironmentVariable.getProperty(userId + userType +"@") != null &&
                "true".equals(EnvironmentVariable.getProperty(userId + userType +"@", "false")));
    }

    /**
     * 验证String字符串是否为Json数据
     *
     * @param message 接收的文本消息
     * @return
     */
    public final static boolean isJSONValid(String message) {
        try {
            com.alibaba.fastjson.JSONObject.parseObject(message);
        } catch (Exception ex) {
            try {
                com.alibaba.fastjson.JSONObject.parseArray(message);
            } catch (Exception ex1) {
                return false;
            }
        }
        return true;
    }
}
